<?php
/**
 * 资金流水类
 * Created by PhpStorm.
 * User: 王海东
 * Date: 2018/12/17
 * Time: 14:00
 */

namespace app\common\model;
use think\Db;

class CapitalLog
{
    private const TAB_NAME = 'capital_log';
    private const TAB_USER = 'user';

    /**
     * 新增资金流水
     * @author 王海东
     * @date
     * @param int    $user_id   用户id
     * @param float  $change_balance    操作金额
     * @param string $msg       操作描述
     * @param int    $type      资金变动类型 1充值 2提现 3买入 4卖出 5递延费
     * @return bool
     * @throws \Exception
     */
    public function add(int $user_id,float $change_balance,string $msg,int $type)
    : bool {
        try {

            $insert = [
                'user_id'           => $user_id,
                'change_balance'    => $change_balance,
                'msg'               => $msg,
                'type'              => $type,
                'create_time'       => date('Y-m-d H:i:s')
            ];

            $user = new User();
            $data = $user->info($user_id);

            $insert['balance'] = $data['balance'];

            $id = Db::name(self::TAB_NAME)
                    ->insert($insert, false, true);
        } catch (\Exception $e) {
            throw new \Exception("资金流水增加失败");
        }

        return $id ? true : false;
    }

    /**
     * 查询资金流水
     * @author 王海东
     * @date
     * @param int   $admin_id 管理员id
     * @param array $map    检索条件
     *     [
     *          start_time  开始时间
     *          end_time    截止时间
     *          name        用户名或手机号
     *          type        流水类型    1充值 2提现 3买入 4卖出 5递延费
     *          agent_name  管理员名称
     *     ]
     * @param int   $page       页码
     * @param int   $pageSize   页幅
     * @return array
     * @throws \Exception
     */
    public function select(int $admin_id,array $map=[],int $page,int $pageSize)
    :array {

        $db = Db::name(self::TAB_NAME);

        $db->alias('c')->join(self::TAB_USER.' u','c.user_id = u.id');

        if(isset($map['type'])) {
            $db->where('c.type',$map['type']);
        }

        if (isset($map["start_time"])) {
            $db->where("c.create_time", ">= TIME", $map["start_time"]);
        }

        if (isset($map["end_time"])) {
            $db->where("c.create_time", "<= TIME", $map["end_time"]);
        }

        if(isset($map['name'])) {
            $db->where('u.name|u.tel',$map['name']);
        }

        $a      = new Admin();
        $ids    = $a->getIds($admin_id);

        if(isset($map['agent_name'])) {

            $agent = $a->getAdminByName($map['agent_name']);
            if($agent) {
                $agent_id = $agent['id'];
                if(!in_array($agent_id,$ids)) {
                    $ids = 0;
                } else {
                    $ids = $a->getIds($agent_id);
                }
            } else {
                $ids = 0;
            }
        }

        $db->where('u.admin_id','in',$ids);


        //查询总数
        $count = $db->count("c.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        try {
            $list = $db->field([
                    'c.change_balance',
                    'c.balance',
                    'c.msg',
                    'c.type',
                    'c.create_time',
                    'u.tel',
                    'u.name',
                    'u.admin_id'
                ])
                    ->order('c.create_time', 'desc')
                    ->page($page,$pageSize)
                    ->select();

            $a          = new Admin();
            $admin      = $a->getAdmin();

            foreach ($list as $key => $val) {
                $list[$key]['admin_name']     = $admin[$val['admin_id']]['name'];
            }

            return [
                "count" => $count,
                "list"  => $list,
            ];
        } catch (\Exception $e) {
            throw new \Exception('查询错误');
        }
    }

    /**
     * 用户资金流水
     * @author 王海东
     * @date
     * @param int $user_id  用户id
     * @param string $type     流水类型    1充值 2提现 3买入 4卖出 5递延费
     * @param int $page     页码
     * @param int $pageSize 页幅
     * @return array
     * @throws \Exception
     */
    public function userList(int $user_id,string $type,int $page,int $pageSize)
    :array {
        $db = Db::name(self::TAB_NAME);

        $db->alias('c')->join(self::TAB_USER.' u','c.user_id = u.id');

        if($type) {
            $db->where('c.type',$type);
        }

        $db->where('c.user_id',$user_id);

        //查询总数
        $count = $db->count("c.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        try {
            $list = $db->field([
                'c.change_balance',
                'c.balance',
                'c.msg',
                'c.type',
                'c.create_time',
                'u.tel',
                'u.name',
            ])
                       ->order('c.create_time', 'desc')
                       ->page($page,$pageSize)
                       ->select();

            return [
                "count" => $count,
                "list"  => $list,
            ];
        } catch (\Exception $e) {
            throw new \Exception('查询错误');
        }
    }
}